package top.yueyazhui.vhr.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.yueyazhui.vhr.model.Employee;
import top.yueyazhui.vhr.model.MailSendConstant;
import top.yueyazhui.vhr.model.MailSendLog;
import top.yueyazhui.vhr.service.EmployeeService;
import top.yueyazhui.vhr.service.MailSendLogService;

import java.util.Date;
import java.util.List;

@Component
public class MailSendTask {

    public static final Logger LOGGER = LoggerFactory.getLogger(MailSendTask.class);

    @Autowired
    MailSendLogService mailSendLogService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    EmployeeService employeeService;

    @Scheduled(cron = "0/10 * * * * ?")
    public void mailResendTask() {
        List<MailSendLog> mailSendLogs =  mailSendLogService.getMailSendLogsByStatus();
        mailSendLogs.forEach((mailSendLog) -> {
            if (mailSendLog.getCount() >= MailSendConstant.MAX_TRY_COUNT) {
                // 直接设置该条消息发送失败
                mailSendLogService.updateMailSendLogStatus(mailSendLog.getMsgId(), 2);
            } else {
                mailSendLogService.updateCount(mailSendLog.getMsgId(), new Date());
                Employee employee = employeeService.getEmployeeById(mailSendLog.getEmpId());
                rabbitTemplate.convertAndSend(MailSendConstant.MAIL_EXCHANGE_NAME, MailSendConstant.MAIL_ROUTING_KEY_NAME, employee, new CorrelationData(mailSendLog.getMsgId()));
            }
        });
    }
}
